//
//  YTHomeDetailController.m
//  yitaicaijing
//
//  Created by DIANGHONG on 2018/7/16.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//



#import "YTHomeDetailController.h"
#import <WebKit/WebKit.h>
#import "YTHDetailHeaderView.h"
#import "UIImage+DHNewImage.h"
#import "YTHDBottomView.h"
#import "YTDetailTipCell.h"
#import "YTHDCommentCell.h"
#import "YTDHHeaderView.h"
#import "YTRecomArticleCell.h"
#import "YTEditCommentView.h"
#import "YTHotCommFooterView.h"
#import "YTHDHotCommentController.h"
#import <YBPopupMenu.h>
#import <Lottie/LOTAnimationView.h>
#import "YTArticleWebCell.h"
#import "YTAuthorInfoController.h"
#import "YTHomeDLoadingView.h"

NSString *YTHTipCellID = @"YTHTipCellID";
NSString *YTHDCellID = @"YTHDCellID";
NSString *YTDHCommCellID = @"YTDHCommCellID";
NSString *YTRecomArticleCellID = @"YTRecomArticleCellID";

@interface YTHomeDetailController ()<WKNavigationDelegate,UITableViewDataSource, UITableViewDelegate, YBPopupMenuDelegate >

@property(nonatomic ,strong)UITableView *tableView;

@property(nonatomic ,strong)YTHDBottomView *bottomView; // 底部视图

@property(nonatomic ,strong)YTHDetailHeaderView *headerView; // 文章作者视图

@property(nonatomic ,strong)YTEditCommentView *editView; // 评论视图

@property(nonatomic ,strong)YTHomeDetailModel *model;

@property(nonatomic ,assign)int page;

@property(nonatomic ,strong)YTDHNewComment *commentNew;

@property(nonatomic ,strong)UIButton *changeTxtButton;

@property(nonatomic ,strong)YTHomeDLoadingView *loadingView; // 加载动画视图

@property(nonatomic ,assign)CGFloat webViewHeight;

@end

@implementation YTHomeDetailController


// lazy loadingView
- (YTHomeDLoadingView *)loadingView
{
    if (!_loadingView) {
        _loadingView = [[YTHomeDLoadingView alloc] init];
        _loadingView.frame = kScreenBounds;
    }
    return _loadingView;
}


- (void)setModel:(YTHomeDetailModel *)model
{
    _model = model;
    
    [self.tableView reloadData];
}

// lazy bottomView
- (YTHDBottomView *)bottomView
{
    if (!_bottomView) {
        CGFloat phoneX = KIsiPhoneX ? 22 : 0;
        
        _bottomView = [YTHDBottomView bottomViewWithFrame:CGRectMake(0,kScreenHeight - 49 - phoneX,
                                                                     kScreenWidth, 49 + phoneX)];
        __weak typeof(self) WeakSelf = self;
        
        _bottomView.scrollButtonClick = ^(BOOL selected) {
            
            if (WeakSelf.commentNew.list.count > 0) {
                 selected ? [WeakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:4] atScrollPosition:UITableViewScrollPositionTop animated:true] : [WeakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:true];
            }else{
                if (WeakSelf.tableView.contentSize.height > WeakSelf.tableView.frame.size.height && selected)
                    
                {
                    
                    CGPoint offset = CGPointMake(0, self.tableView.contentSize.height -self.tableView.frame.size.height);
                    
                    [WeakSelf.tableView setContentOffset:offset animated:true];
                    
                }else{
                    [WeakSelf.tableView setContentOffset:CGPointMake(0,0) animated:NO];
                
                }
            }
           
        };
        
        _bottomView.shouldLoginBlock = ^{
//            YTLoginViewController *logVC = [[YTLoginViewController alloc] init];
//            [WeakSelf.navigationController pushViewController:logVC animated:true];
        };
        //_bottomView.backgroundColor = UIColor.randomColor;
        _bottomView.begainEditing = ^{
            
            if (!YTNetworkManager.shareManager.account.auth) {
                YTLoginViewController *logVC = [[YTLoginViewController alloc] init];
                [WeakSelf.navigationController pushViewController:logVC animated:true];
                return ;
            }
            
            [WeakSelf.view insertSubview:WeakSelf.editView aboveSubview:WeakSelf.bottomView];
        
            [WeakSelf.editView showKeybord];
            
        };
        
        _bottomView.shareButtonClick = ^{
            //在分享按钮绑定如下触发代码
            //显示分享面板
            [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
                // 根据获取的platformType确定所选平台进行下一步操作
                [WeakSelf shareWebPageToPlatformType:platformType];//新增代码
            }];
        };
    }
    return _bottomView;
}


//定义实现的方法
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    //NSString* thumbURL =  @"https://mobile.umeng.com/images/pic/home/social/img-1.png";
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.model.post_title descr:self.model.post_digest thumImage:self.model.purl];
    //设置网页地址
    shareObject.webpageUrl = self.model.shareurl;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
            [self.view showErrorWithTipStr:@"分享失败"];
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                
                [YTNetworkManager.shareManager requestSiginWithType:@"7"
                                                            post_id:self.ID
                                                         completion:^(BOOL isSucc, NSString *StatusInfo)
                {
                    if (!isSucc) {
                        [self.view showErrorWithTipStr:StatusInfo];
                        return ;
                    }
                    
                    [self.view showAwardWithTipStr:[NSString stringWithFormat:@"分享成功 +%@ 算力",StatusInfo]];
                }];
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
        NSLog(@"分享出错%@",error);//修改代码
    }];
}

// lazy editView
- (YTEditCommentView *)editView
{
    if (!_editView) {
        
        __weak typeof(self) WeakSelf = self;
        _editView = [YTEditCommentView commentViewWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 173)];
        _editView.ID = self.model.tid;
        _editView.closeButtonClick = ^(BOOL isComment) {
            [UIView animateWithDuration:0.25 animations:^{
                WeakSelf.editView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                [WeakSelf.editView removeFromSuperview];
            }];
            
            if (isComment) {
                WeakSelf.page = 1;
                [WeakSelf loadNewCommentList];
                WeakSelf.model.comment_count = [NSString stringWithFormat:@"%d",WeakSelf.model.comment_count.intValue + 1];
                WeakSelf.bottomView.model = WeakSelf.model;

            }

        };
    }
    return _editView;
}



// lazy tableView
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        self.headerView = [YTHDetailHeaderView headerViewWithFrame:CGRectMake(0, 0, kScreenWidth, 180)];
        _tableView.tableHeaderView = self.headerView;

        
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewCommentList)];
        _tableView.mj_footer = footer;
        
        _tableView.sectionFooterHeight = 34;
        //[footer ]
        
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [_tableView registerClass:[YTArticleWebCell class] forCellReuseIdentifier:YTHDCellID];
        [_tableView registerClass:[YTDetailTipCell class] forCellReuseIdentifier:YTHTipCellID];
        [_tableView registerNib:[UINib nibWithNibName:@"YTHDCommentCell" bundle:nil]
                                        forCellReuseIdentifier:YTDHCommCellID];
        [_tableView registerNib:[UINib nibWithNibName:@"YTRecomArticleCell" bundle:nil]
                        forCellReuseIdentifier:YTRecomArticleCellID];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
  

    self.page = 1;
    
    [self.view addSubview:self.tableView];
    
    //[self.loadingView play];

    [self loadData];

    
    self.changeTxtButton = [[UIButton alloc] init];
    [self.changeTxtButton setImage:[UIImage imageNamed:@"ztdx"] forState:UIControlStateNormal];
    [self.changeTxtButton setImage:[UIImage imageNamed:@"ztdx_dj"] forState:UIControlStateSelected];
    
    [self.changeTxtButton addTarget:self action:@selector(txtChangeSize:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.changeTxtButton];
    
    
    
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(keyBordChange:)
                                               name:UIKeyboardWillChangeFrameNotification
                                             object:nil];
    [self setupUI];
    
    // 作者头像 点击跳转
    __weak typeof(self) WeakSelf = self;
    self.headerView.authorIconClickBlock = ^(NSString *ID) {
        YTAuthorInfoController *infoVC = [[YTAuthorInfoController alloc] init];
        infoVC.user_id = ID;
        [WeakSelf.navigationController pushViewController:infoVC animated:true];
    };
}

#pragma mark: - 改变字体按钮监听
- (void)txtChangeSize:(UIButton *)sender
{
    
    YBPopupMenu * popupMenu = [YBPopupMenu showRelyOnView:self.changeTxtButton titles:@[@"大字体",@"中字体",@"小字体"] icons:nil menuWidth:120 delegate:self];
    popupMenu.dismissOnSelected = YES;
    popupMenu.isShowShadow = YES;
    
    
}

#pragma mark: - YBPopupMenu delegate
- (void)ybPopupMenu:(YBPopupMenu *)ybPopupMenu didSelectedAtIndex:(NSInteger)index
{
    switch (index)
    {
        case 0: // 大字体
            YTNetworkManager.shareManager.textSize = 150;
            break;
        case 1: // 中字体
            YTNetworkManager.shareManager.textSize = 100;
            break;
        default:
            YTNetworkManager.shareManager.textSize = 60;
            break;
    }
    
    self.changeTxtButton.selected = NO;
    
    YTArticleWebCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    cell.textSize = YTNetworkManager.shareManager.textSize;
    [self.tableView reloadData];
}

#pragma mark: - 键盘弹出通知
- (void)keyBordChange:(NSNotification *)n
{
    CGRect keybordFrame = [n.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    if (keybordFrame.origin.y == kScreenHeight) {
        self.editView.closeButtonClick(false);
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        self.editView.transform = CGAffineTransformMakeTranslation(0,  -keybordFrame.size.height - self.editView.bounds.size.height);
    }];
}
#pragma mark: - 需要登录通知
- (void)shouldLogon:(NSNotification *)n
{
    YTLoginViewController *logVC = [[YTLoginViewController alloc] init];
    logVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:logVC animated:true];
}

- (void)dealloc
{
    [NSNotificationCenter.defaultCenter
     removeObserver:self
     name:kLikeButtonClickNotication
     object:nil];
    
    [NSNotificationCenter.defaultCenter removeObserver:self
                                            name:UIKeyboardDidChangeFrameNotification
                                                object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(shouldLogon:)
                                               name:kShouldLoginNotication
                                             object:nil];
    
    self.extendedLayoutIncludesOpaqueBars = YES;
    
    [MobClick beginLogPageView:[NSString stringWithFormat:@"文章%@",self.ID]];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    // 移除登陆等通知
    [NSNotificationCenter.defaultCenter
     removeObserver:self
     name:kShouldLoginNotication
     object:nil];
    
    [MobClick endLogPageView:[NSString stringWithFormat:@"文章%@",self.ID]];

}

#pragma mark: - 加载数据
- (void)loadData
{

    [YTNetworkManager.shareManager requestArticleDetailWithID:self.ID
                                                   completion:^(YTHomeDetailModel *model, BOOL isSucc, NSString *error)
     {
         //[NSThread sleepForTimeInterval:2];
         if (!isSucc) {
             [self.view showTipWithTipStr:error];
             return ;
         }
         
         
         [YTNetworkManager.shareManager requestHotCommentWithTid:self.ID
                                                           paged:1
                                                       page_size:@"5"
                                                      completion:^(YTDHNewComment *comModel, BOOL isSucc, NSString *error)
          {
              if (!isSucc) {
                  [self.view showTipWithTipStr:error];
                  return ;
              }
              
              
              [YTNetworkManager.shareManager requestRelatArticleWithTid:self.ID
                                                                  paged:1
                                                              page_size:5
                                                             completion:^(NSArray *list, BOOL isSucc, NSString *classID, NSString *error)
               {
                   if (!isSucc) {
                       [self.view showTipWithTipStr:error];
                       return ;
                   }
                   
             
                   [self.loadingView removeFromSuperview];
                   [model.reward[@"is_reward"] boolValue] ? [self.view showAwardWithTipStr:[NSString stringWithFormat:@"阅读文章 +%@算力",model.reward[@"money"]]] : nil;
//                   [self dealNewsDetail:model.post_content];
                   self.headerView.model = model;
                   self.model = model;
                   self.bottomView.model = model;
                   self.model.hotCommentList = comModel.list;
                   self.model.recomArticleList = list;
                   self.model.classID = classID;
                   self.model.tid = self.ID;
                   [self.tableView.mj_footer beginRefreshing];
                   [self.tableView reloadData];
               }];
          }];
     }];
    
}


#pragma mark: - 下拉加载最新评论
- (void)loadNewCommentList
{

    if (self.page != 1) {
        if (self.page > self.commentNew.total_pages.intValue) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            return;
        }
    }
   
    [YTNetworkManager.shareManager requestHDCommentListWithTid:self.ID
                                                         paged:self.page
                                                    completion:^(YTDHNewComment *model, BOOL isSuccess, NSString *error)
    {
        if (!isSuccess) {
            [self.view showTipWithTipStr:error];
            return ;
        }
        
        if (self.page == 1) {
            self.commentNew = model;
        }else{
            self.commentNew.list = [self.commentNew.list arrayByAddingObjectsFromArray:model.list];
        }
        
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
        self.page++;
    }];
}


#pragma mark: - 设置界面
- (void)setupUI
{

    self.navigationItem.titleView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"icon_logo"]];
    
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, self.bottomView.bounds.size.height, 0);
    
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage dh_setNavImageName:@"倛袨1"]
                                                                              style:UIBarButtonItemStylePlain
                                                                             target:self
                                                                             action:@selector(backButtonClick)];
    
    [self.view addSubview:self.bottomView];
    
    [self.view insertSubview:self.loadingView aboveSubview:self.bottomView];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
  

}



- (void)backButtonClick
{
    NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
    if([[pushJudge objectForKey:@"push"]isEqualToString:@"push"]) {
        [self dismissViewControllerAnimated:true completion:nil];
        [pushJudge setObject:@""forKey:@"push"];
    }else{
         [self.navigationController popViewControllerAnimated:true];
    }
   
}

#pragma mark: - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 2:
            return self.model.recomArticleList.count;
            break;
        case 3:
            return self.model.hotCommentList.count;
            break;
        case 4:
            return self.commentNew.list.count;
            break;
        default:
            return 1;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = nil;
    switch (indexPath.section)
    {
        case 0:
            cellID = YTHDCellID;
            break;
        case 1:
            cellID = YTHTipCellID;
            break;
        case 2:
            cellID = YTRecomArticleCellID;
            break;
        case 3:
        case 4:
            cellID = YTDHCommCellID;
            break;
        default:
            break;
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    
    switch (indexPath.section)
    {
        case 0:
        {   __weak typeof(self) WeakSelf = self;
            [(YTArticleWebCell *)cell setPost_content:self.model.post_content];
            
            [(YTArticleWebCell *)cell setReloadWebHeightBlock:^(CGFloat height) {
                WeakSelf.webViewHeight = height;
                [WeakSelf.tableView reloadData];
            }];
        }
            break;
        case 1:
            [(YTDetailTipCell *)cell setModel:self.model];
            break;
        case 2:
            [(YTRecomArticleCell *)cell setModel:self.model.recomArticleList[indexPath.row]];
            break;
        case 3:
            [(YTHDCommentCell *)cell setCommentModel:self.model.hotCommentList[indexPath.row]];
            [(YTHDCommentCell *)cell setTid:self.ID];
            break;
        case 4:
            [(YTHDCommentCell *)cell setCommentModel:self.commentNew.list[indexPath.row]];
            [(YTHDCommentCell *)cell setTid:self.ID];
            break;
    }

    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;

}





#pragma mark: - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
  
    if(indexPath.section == 0){
        /* 通过webview代理获取到内容高度后,将内容高度设置为cell的高 */
        return self.webViewHeight;
    }else{
        if (indexPath.section == 1) {
            CGFloat row = self.model.newsTerms.count / 5 + 1;
            CGFloat height = row * 40;
            return 80 + height;
        }
        return 100;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    // 相关文章
    if (indexPath.section == 2) {
        YTHomeDetailController *detailVC = [[YTHomeDetailController alloc] init];
        detailVC.ID = self.model.recomArticleList[indexPath.row].ID;
        [self.navigationController pushViewController:detailVC animated:true];
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    switch (section)
    {
        case 3:
            return [self creatHeaderWithTip:@"热门评论"];
            break;
        case 4:
            return [self creatHeaderWithTip:@"最新评论"];
            break;
        case 2:
            return [self creatHeaderWithTip:@"相关文章"];
            break;
        default:
            return [[UIView alloc] init];
            break;
    }
    
   
}

#pragma mark: - scroll view delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.headerView.bounds.size.height-88 == scrollView.contentOffset.y) {
       NSLog(@"消失了");
    }else{
        
    }
}
#pragma mark: - 创建headerView
- (YTDHHeaderView *)creatHeaderWithTip:(NSString *)tip
{
    YTDHHeaderView *header = [YTDHHeaderView headerViewWithTitle:tip];
    return header;
}




- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    if (section == 3 || section == 4 || section == 2) {
        return 47;
    }
    return 0;
}



- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 3) {
        
        YTHotCommFooterView *foot = [YTHotCommFooterView footView];
        
        foot.MoreHotCommentClick = ^{
            
            if (self.model.hotCommentList.count == 0) {
                [self.view showTipWithTipStr:@"没有更多评论哦"];
                return ;
            }
            
            YTHDHotCommentController *vc = [[YTHDHotCommentController alloc] init];
            vc.ID = self.ID;
            [self.navigationController pushViewController:vc animated:true];
        };
        
        return foot;
    }
    return [[UIView alloc] init];
}





@end
